const express = require('express');
const path = require('path');
const staticResource = require('./static_resource_manage.js');
const article_server = require('./article_server.js');
const source_code_server = require('./source_code_server.js');
const expressMobile = require('./expressMobile.js');
const htmlConfig = require('./config/htmlConfig.js');

let expressApp = function () {
    let app = express();
    let port = 80;
    app.listen(port, function () {
        let host = 'localhost';
        console.log('Example app listening at http://%s:%s', host, port);
    });

    app.get('/',function (req,res) {
        // console.log(req.url);
        res.sendFile(path.resolve('../TaskAndModule/dist_prod/redirect.html'));
    });

    app.post('/redirect',function (req,res) {
        /*接收重定向页面的请求*/
        /*然后根据发送的user-agent信息判断访问端类型*/
        // console.log(req.headers['user-agent']+'\n');
        try{
            let user_agent = req.headers['user-agent'];
            let Android = new RegExp('Android').test(user_agent);
            let Mobile = new RegExp('Mobile').test(user_agent);
            if(Android&&Mobile){
                res.send(htmlConfig.mIndex);
            }else{
                res.send(htmlConfig.index);
            }
        }catch (err){
            console.error('position:expressApp->/redirect');
            console.error(err);
        }
    });


    /*
    * kfm和mobile两个参数已经失去了意义
    * 为了避免对使用这两个参数的函数进行大的改动,给他们赋值空字符串
    * */
    let kfm = '';
    let mobile = '';
    let dist_prod = '../TaskAndModule/dist_prod';
    /*
    * _app.use(_express.static(path.resolve('../redirect')))为重定向主页,负责针对pc和移动端分配不同的主页
    * 没写挂载路径的为根路径
    * */
    staticResource.init(express, app);
    staticResource.defaultStaticResource(dist_prod);
    app.use(express.static(path.resolve(dist_prod)));
    article_server(app, kfm);
    source_code_server(app, kfm);
    expressMobile(app, mobile, dist_prod);

};


module.exports = expressApp;

